<?php

namespace App\Admin\Controllers;

use App\Models\ProductClass;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Show;
use Encore\Admin\Traits\ModelTree;

class ProductClassController extends AdminController
{
    use ModelTree;
    /**
     * Title for current resource.
     *
     * @var string
     */
    protected $title = '商品分类';

   public function index(Content $content)
   {
       return \Admin::content(function (Content $content) {
           $content->header('产品分类');
           $content->body(ProductClass::tree());
       });
   }


    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(ProductClass::findOrFail($id));

        $show->field('id', __('Id'));
        $show->field('title', __('Title'));
        $show->field('parent_id', __('Parent id'));
        $show->field('order', __('Order'));
        $show->field('created_at', __('Created at'));
        $show->field('updated_at', __('Updated at'));

        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new ProductClass());

        $form->text('title', "分类名称")->rules('required');
        $form->select('parent_id',"所属分类")->options(ProductClass::selectOptions(function ($model) {
           return $model->where('order','<',3);
        }))->required();

        $form->saving(function (Form $form) {
            $parent_id=$form->parent_id;
            if ((int)$parent_id!=0) {
                //不是一级菜单
                /** @var ProductClass $category */
                $category=$form->model();
                $form->model()->order=$category->getClassLevel($parent_id)+1;
            }
        });
        return $form;
    }
}
